<?php
namespace app\services;
use Yii;
use app\models\Modify;

class ModifyService extends BaseService {
	public function init() {
        parent::init();
    }
    public function saveModify($oldData,$newData,$model,$addKey=[],$delKey=[]){
    	$data['user_id'] = $this->S('user_id');
    	$data['user_name']  = $this->S('user_name');
    	$data['model'] = $model;
        $diffData = $this->getDiffData($oldData,$newData,$addKey,$delKey);
        if(isset($diffData['newData']['id']) && count($diffData['newData'])==1)  return;
    	$data['properties'] = json_encode($diffData['newData'], JSON_UNESCAPED_UNICODE);
    	$data['old_properties'] = json_encode($diffData['oldData'], JSON_UNESCAPED_UNICODE);
    	$this->saveData('Modify',$data);
    }

    public function getDiffData($oldData,$newData,$addKey,$delKey){
        $dataDiff = array_diff_assoc($oldData,$newData);
        $keyDiff = array_keys($dataDiff);
        $keyDiff = array_merge($keyDiff,$addKey);
        foreach ($oldData as $k1 => $v1) {
            if(!in_array($k1,$keyDiff) || in_array($k1,$delKey)){
                unset($oldData[$k1]);
            }
        }
        foreach ($newData as $k2 => $v2) {
            if(!in_array($k2,$keyDiff) || in_array($k2,$delKey)){
                unset($newData[$k2]);
            }
        }
        return [
            'oldData' => $oldData,
            'newData' => $newData
        ];

    }

    public function getModifyData(){
    	$where = 'status=0';
    	$modifyData = $this->getAll('Modify',$where);
    	return $modifyData;
    }

    public function sendModifyMail($receiver){
    	$modifyData = $this->getModifyData();
    	if(empty($modifyData)){
    		exit();
    	}
        $title = "
        <!DOCTYPE html>
        <head>
        <meta charset='utf-8'>
        </head>

        <body>
        <thead>
			<tr>
				<th>用户名</th>
				<th>模型</th>
				<th>操作前数据</th>
				<th>操作后数据</th>
				<th>时间</th>
			</tr>
		</thead>
        ";
        $body = '';
        foreach ($modifyData as $key => $value) {
        	$body.= '<tr><td>'.$value['user_name'].'</td>
        	             <td>'.$value['model'].'</td>
        	             <td>'.$value['old_properties'].'</td>
        	             <td>'.$value['properties'].'</td>
        	             <td>'.$value['last_update'].'</td>
        	         </tr>';
        }
        $content = '<table border="1">'.$title.$body.'<table></body></html>';
        $mail= Yii::$app->mailer->compose();
		$mail->setTo($receiver);  
		$mail->setSubject("admath-UI数据操作记录");  
		//$mail->setTextBody('zheshisha ');   //发布纯文字文本
		$mail->setHtmlBody($content);    //发布可以带html标签的文本
		if($mail->send()){
			$data['status'] = 1;
		    $this->saveOn('Modify',['status' => 0],$data);
		    echo 'success'; 
		}else{
			echo 'false';
		}  
    }
}